package com.rmb.service.impl;

import com.rmb.mapper.LogAddressMapper;
import com.rmb.service.LogAddressService;
import com.rmb.util.AddressUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName LogAddressServiceImpl
 * @Description TODO
 * @Author lvshook
 * @Date 2021/1/20 10:56
 * @Version 1.0
 **/

@Service
public class LogAddressServiceImpl implements LogAddressService {

    /**
     * mapper对象
     */
    @Autowired(required = false)
    private LogAddressMapper logAddressMapper;

    /**
     * 查询近一次登录信息
     * @param uid
     * @return
     */
    @Override
    public Date findone(Long uid) {
        return logAddressMapper.findone(uid);
    }

    /**
     * 获取地址
     * 返回map
     * @param request
     * @return
     */
    @Override
    public Map getip(HttpServletRequest request) {

            String unknown="unknown";
            String ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                String[] iP ={"127.0.0.1","0:0:0:0:0:0:0:1"};
                if (iP [0].equals(ip) || iP [1].equals(ip)) {
                    //根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ip = inet.getHostAddress();
                }
            }
            //根据ip查到ip所在地址
            String address = AddressUtils.getaddressbyip(ip);
            //map
            Map map = new HashMap(16);
            map.put("ip",ip);
            map.put("address",address);

            return map;

        }

    /**
     * 登录记录表
     * @param uid
     * @return
     */
    @Override
    public List logAll(Long uid) {
        return logAddressMapper.logAll(uid);
    }


}
